package test.baojia.act.business;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.Assert;

import java.util.Properties;

public class LoginBusiness extends Business {

    /**
     * context 依赖 userName 、 password。
     * @param context
     * @param driver
     * @param resource
     * @param parentContext
     */
    @Override
    public void run(JSONObject context, WebDriver driver, Properties resource, JSONObject parentContext) throws Exception {
        super.run(context , driver , resource, parentContext);

        final String userName = (String) context.get("userName");
        final String password = (String) context.get("password");
        final String loginName = (String) context.get("loginName");

        Assert.assertTrue(StringUtils.isNotBlank(userName));
        Assert.assertTrue(StringUtils.isNotBlank(password));
        Assert.assertTrue(StringUtils.isNotBlank(loginName));

        final String url = resource.getProperty("login.url");
        driver.get(url);

        final String frame = resource.getProperty("login.frame");
        if(StringUtils.isNotBlank(frame)){
            driver.switchTo().frame(frame);
        }

        final String loginButtonXpath = resource.getProperty("login.loginButtonXpath");
        this.newWebDriverWait(null)
                .until(ExpectedConditions.presenceOfElementLocated(By.xpath(loginButtonXpath)));

        final String usernameID = resource.getProperty("login.usernameID");
        final String passwordID = resource.getProperty("login.passwordID");
        driver.findElement(By.id(usernameID)).sendKeys(userName);
        driver.findElement(By.id(passwordID)).sendKeys(password);

        if(StringUtils.isNotBlank(loginButtonXpath)){
            driver.findElement(By.xpath(loginButtonXpath)).click();
        }

        final String loginNameCssSelector = resource.getProperty("login.loginName");
        this.newWebDriverWait(null)
                .until(ExpectedConditions.textToBe(By.cssSelector(loginNameCssSelector) , loginName));

        this.newWebDriverWait(null)
                .until(ExpectedConditions.presenceOfElementLocated(By.id("menu")));
    }
}